package a66weding.com.jiehuntong.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.tedcoder.wkvideoplayer.view.SuperVideoPlayer;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.xutils.HttpManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.ElectronicInvitationActivity;
import a66weding.com.jiehuntong.activity.LocalVideoActivity;
import a66weding.com.jiehuntong.activity.VideoRecorderActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SimpleBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.VideoBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.LogUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;

/**
 * 谱写故事（视频故事）
 */
public class VideoStoryFragment extends Fragment implements View.OnClickListener, OnNetResultListener {

    private static final int VIDEOFILE = 1, RECORDINGVIDEO = 2, PERMISSION_SDCARD = 4, PERMISSION_CAMERA = 5;
    private Dialog dialog;

    private TextView have_video_story_tv;
    private LinearLayout no_video_story_ll;
    private ImageView video_bg_iv;
    private SuperVideoPlayer videoView;
    private View mPlayBtnView;
    private ImageButton video_del_button;
    private Context context;
    private View mContainer;
    private VideoBean mVideoBean;
    private Button btn_up_video;
    private FrameLayout video_story_fl;
    private int uId;
    private String videoStoryName;


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getActivity();
        if (mContainer == null) {
            mContainer = inflater.inflate(R.layout.fragment_video_story, container, false);
            initViews();
            initInfo();
            loadData();
        } else {
            if (mContainer.getParent() != null) {
                ((ViewGroup) mContainer.getParent()).removeView(mContainer);
            }
        }
        return mContainer;
    }

    public void initViews() {
        btn_up_video = (Button) mContainer.findViewById(R.id.btn_up_video);
        btn_up_video.setOnClickListener(this);
        videoView = (SuperVideoPlayer) mContainer.findViewById(R.id.video);
        videoView.setVideoPlayCallback(mVideoPlayCallback);
        mPlayBtnView = mContainer.findViewById(R.id.play_btn);
        mPlayBtnView.setOnClickListener(this);
        video_del_button = (ImageButton) mContainer.findViewById(R.id.video_del_button);
        video_del_button.setOnClickListener(this);
        have_video_story_tv = (TextView) mContainer.findViewById(R.id.have_video_story_tv);
        no_video_story_ll = (LinearLayout) mContainer.findViewById(R.id.no_video_story_ll);
        video_bg_iv = (ImageView) mContainer.findViewById(R.id.video_bg_iv);
        video_story_fl = (FrameLayout) mContainer.findViewById(R.id.video_story_fl);

    }

    private void initInfo() {
        uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        setVideoVisibility(false);
    }

    private void loadData() {
        String url = RequestCode.SURL + RequestCode.GETVIDEO + uId;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, VideoBean.class, "");
        HttpHandleUtil.executeCommonGet(getActivity(), httpRequestBean);
    }

    //删除视频
    private void removeVideo() {
        String url = RequestCode.SURL + RequestCode.REMOVEVIDEO + uId;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, SimpleBean.class, "");
        HttpHandleUtil.executeCommonGet(getActivity(), httpRequestBean);
    }

    /**
     * 播放器的回调函数
     */
    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        /**
         * 播放器关闭按钮回调
         */
        @Override
        public void onCloseVideo() {
            closeVideo();
        }

        /**
         * 播放器横竖屏切换回调
         */
        @Override
        public void onSwitchPageType() {
//            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                videoView.setPageType(MediaController.PageType.SHRINK);
//            } else {
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//                videoView.setPageType(MediaController.PageType.EXPAND);
//            }
        }

        /**
         * 播放完成回调
         */
        @Override
        public void onPlayFinish() {
            closeVideo();
        }
    };

    private void closeVideo() {
        videoView.close();//关闭VideoView
        mPlayBtnView.setVisibility(View.VISIBLE);
        videoView.setVisibility(View.GONE);
        resetPageToPortrait();
    }

    /***
     * 恢复屏幕至竖屏
     */
    private void resetPageToPortrait() {
//        if (getActivity().getRequestedOrientati
// () == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//            videoView.setPageType(MediaController.PageType.SHRINK);
//        }
    }

    public void showVideoSelect() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.activity_tools_dialog_photo, null);
        Button photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);
        photoBtn.setText("本地上传视频");
        Button cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);
        cameraBtn.setText("拍摄");
        Button quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);
        if (dialog == null) {
            dialog = new Dialog(getActivity(), R.style.transparentFrameWindowStyle);
        }
        photoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                showVideo();
            }
        });
        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                showCamera();
            }

        });
        quxiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
    private static final String TAG = "权限";
    /**
     * 录制视频
     */
    public void showCamera() {
        if( ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
               &&ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
              &&ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED
                ) {
            Log.i(TAG, "有权限");
            //自己的录像机界面
           startActivityForResult(new Intent(getActivity(), VideoRecorderActivity.class), 696);
        } else {
            Log.i(TAG, "没有权限,准备申请");
           ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA}, PERMISSION_CAMERA);
        }
    }
    /**
     * 视频选择选取
     */
    private void showVideo() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请MOUNT_UNMOUNT_FILESYSTEMS权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_SDCARD);
        } else {
            //自己的视频浏览界面
            Intent intent = new Intent(getActivity(), LocalVideoActivity.class);
            this.startActivityForResult(intent, 369);
/*      系统文件浏览器
       Intent intent = new Intent(Intent.ACTION_PICK, null);
            //下面这句指定调用相机拍照后的照片存储的路径
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "video*//*");
            this.startActivityForResult(intent, VIDEOFILE);*/
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_SDCARD) {
            if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                showVideo();
            } else {
                CUtils.showToast("请打开手机读取权限后在操作");
            }
        } else if (requestCode == PERMISSION_CAMERA) {
            boolean cameraAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED;
            if(cameraAccepted){
                Log.i(TAG, "onRequestPermissionsResult: 审核通过了");
                showCamera();
            }else{
                Log.i(TAG, "onRequestPermissionsResult: 没给");
                //用户授权拒绝之后，友情提示一下就可以了
                CUtils.showToast("请打开手机读写sd卡,相机,音频录制权限后在操作");
            }
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != 0) {
            switch (requestCode) {
                // 文件浏览器视频选择
                case VIDEOFILE:
                    if (data != null) {
                        Uri videoDate = data.getData();
                        String path = getRealFilePath(context, videoDate);
                        final File file = new File(path);
                        if (file != null && file.exists()) {
                            int fileSize = (int) (file.length() * 1.0 / 1024 / 1024);
                            if (fileSize > 100) {
                                CUtils.showToast("选取的视频文件不能超过100M");
                            } else {
                                Tools.showSimpleDialog(context, "是否上传选择的视频", "取消", "确定", new Tools.ClickListenerInterface() {
                                    @Override
                                    public void doConfirm() {
                                        File picFile = getBitmapFromFile(file);
                                        uploadfile(file, picFile);
                                    }

                                    @Override
                                    public void doCancel() {

                                    }
                                });
                            }
                        } else {
                            CUtils.showToast("获取文件失败");
                        }
                    }

                    break;
                case 696://自己的录像机录制界面
                    if (data != null) {
                        String videoPath = data.getStringExtra("videoPath");
                        LogUtil.d("696", videoPath);
                        final File temp = new File(videoPath);
                        if (temp != null && temp.exists()) {
                            Tools.showSimpleDialog(context, "是否上传拍摄视频", "取消", "确定", new Tools.ClickListenerInterface() {
                                @Override
                                public void doConfirm() {
                                    File picFile = getBitmapFromFile(temp);
                                    uploadfile(temp, picFile);
                                }
                                @Override
                                public void doCancel() {
                                }
                            });

                        } else {
                            CUtils.showToast("获取文件失败");
                        }
                    }
                    break;
                case 369://自己的视频浏览界面
                    if (data != null) {
                        final String videoPath = data.getStringExtra("videoPath");
                        if (videoPath != null) {
                            if (!videoPath.endsWith(".mp4") && !videoPath.endsWith(".MP4")) {
                                CUtils.showToast("仅支持MP4格式");
                            } else {
                                final File videofile = new File(videoPath);
                                int fileSize = (int) (videofile.length() * 1.0 / 1024 / 1024);
                                if (fileSize > 100) {
                                    CUtils.showToast("选取的视频文件不能超过100M");
                                } else {
                                    Tools.showSimpleDialog(getActivity(), "是否上传选择的视频文件", "取消", "确定", new Tools.ClickListenerInterface() {
                                        @Override
                                        public void doConfirm() {
                                            File picFile = getBitmapFromFile(videofile);
                                            uploadfile(videofile, picFile);
                                        }
                                        @Override
                                        public void doCancel() {
                                        }
                                    });
                                }
                            }
                        } else {
                            CUtils.showToast("未获得文件路径,选取失败");
                        }

                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private File getBitmapFromFile(File file) {
        /**
         * android系统中为我们提供了ThumbnailUtils工具类来获取缩略图的处理。
         * ThumbnailUtils.createVideoThumbnail(filePath, kind)
         *          创建视频缩略图，filePath:文件路径，kind：MINI_KIND or MICRO_KIND
         * ThumbnailUtils.extractThumbnail(bitmap, width, height)
         *          将bitmap裁剪为指定的大小
         * ThumbnailUtils.extractThumbnail(bitmap, width, height, options)
         *          将bitmap裁剪为指定的大小，可以有参数BitmapFactory.Options参数
         *
         */
        Bitmap bitmap = null;
        bitmap = ThumbnailUtils.createVideoThumbnail(file.getPath(), MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);

        //获取图片后，我们队图片进行压缩，获取指定大小
        if (bitmap != null) {
            //裁剪大小
//            bitmap = ThumbnailUtils.extractThumbnail(bitmap, Utils.dip2px(getActivity(),300) , Utils.dip2px(getActivity(),200));
        } else {//如果为空，采用我们的默认图片
            bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg_loadimage);
        }
        String videoPicName = "videoPic_" + (System.currentTimeMillis() + "").hashCode() + ".png";// 将要保存图片的路径
        File filePic = FileUtil.getDefaultFile(videoPicName);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePic));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePic;
    }

    /**
     * 根据uri获取file地址
     *
     * @param context
     * @param uri
     * @return
     */
    private String getRealFilePath(final Context context, final Uri uri) {

        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private void uploadfile(final File saveFile, final File filePic) {
        // 视频上传地址
        final String url = RequestCode.SURL + RequestCode.UPLOADVIDEO + uId;
//        btn_up_video.setEnabled(false);
        new Thread() {
            @Override
            public void run() {
                long ll = System.currentTimeMillis();
                String result = uploadFile(saveFile, filePic, url);
                long lll = System.currentTimeMillis();
                LogUtil.i("jiehuntong", (lll - ll) + "fffffff");
                Message msg = handler.obtainMessage(0);
                msg.obj = result;
                handler.sendMessage(msg);
            }
        }
//                .start()
        ;

        // 弹框
        Tools.showWaitDialog(getActivity(), "上传中...", false);
        HttpManager xhttp = x.http();
        RequestParams requestParams = new RequestParams(url);
        requestParams.addBodyParameter("img", filePic);
        requestParams.addBodyParameter("img", saveFile);
        final long ll = System.currentTimeMillis();
        xhttp.post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Tools.dismissWaitDialog();
                LogUtil.i("httpUtils", "postResult:" + result);
                long lll = System.currentTimeMillis();
                LogUtil.i("jiehuntong", (lll - ll) + "aaaa");
                Message msg = handler.obtainMessage(0);
                msg.obj = result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Tools.dismissWaitDialog();
                LogUtil.i("httpUtils", "postError:" + ex.toString());
                CUtils.showToast("上传失败 ");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
//                    btn_up_video.setEnabled(true);
//                    btn_up_video.setText("上传");
                    String result = msg.obj.toString();
                    if (!TextUtils.isEmpty(result)) {
                        Gson gson = new Gson();
                        mVideoBean = gson.fromJson(msg.obj.toString(), VideoBean.class);
                        if (mVideoBean != null && mVideoBean.getResCode() != null) {
                            if (mVideoBean.getResCode().equals("0000")) {
                                CUtils.showToast("上传成功");
                                setVideo();
                                getActivity().sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                            } else {
                                CUtils.showToast(mVideoBean.getMsg());
                            }
                        }
                    } else {
                        CUtils.showToast("上传失败");
                    }
                    break;
                case 1:
                    Bundle b = msg.getData();
                    int scale = (int) (b.getLong("count") * 1.0 / b.getLong("total") * 100);
                    String content = "上传 " + scale + "%";
                    if (!content.equals(btn_up_video.getText().toString()) && scale < 91) {
                        btn_up_video.setText(content);
                    }
                    break;
                case 12:
                    int width = msg.arg1;
                    int height = msg.arg2;
                    if (width > 0 || height > 0 || no_video_story_ll.getWidth() > 0) {
                        int targetWidth = no_video_story_ll.getWidth();
                        int targetHeight = no_video_story_ll.getHeight() - Utils.dip2px(getActivity(), 50f);
                        double xScale = (double) width / (double) targetWidth;// 宽度比例
                        double yScale = (double) height / (double) targetHeight;// 高度比例
                        int x, y;
                        if (xScale < yScale) {
                            x = (int) (targetHeight * 1.0 * width / height);
                            y = targetHeight;
                        } else {
                            x = targetWidth;
                            y = (int) (targetWidth * 1.0 * height / width);
                        }
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(x, y);
                        video_story_fl.setLayoutParams(params);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public String uploadFile(File file, File filePic, String RequestURL) {
        String result = "";
        String BOUNDARY = UUID.randomUUID().toString();
        //边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(60 * 100000);
            conn.setConnectTimeout(60 * 100000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", "utf-8");
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if (file != null && filePic != null) {
                //**  当文件不为空，把文件包装并且上传 *//*
                OutputStream outputSteam = conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();

                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);

                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + filePic.getName() + "\"" + LINE_END);
                LogUtil.i("jiehuntong", "pic " + filePic.getName());
                sb.append("Content-Type: application/octet-stream; charset=utf-8" + LINE_END);

                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());

                InputStream isPic = new FileInputStream(filePic);
                byte[] bytes = new byte[1024];
                int len = -1;
                long count = 0;

                while ((len = isPic.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                dos.writeBytes(LINE_END);
                isPic.close();


                InputStream is = new FileInputStream(file);
                sb = new StringBuffer();

                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);

                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END);
                LogUtil.i("jiehuntong", "video " + file.getName());
                sb.append("Content-Type: application/octet-stream; charset=utf-8" + LINE_END);

                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());

                Message msg;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                    count += len;
                    msg = new Message();
                    msg.what = 1;
                    Bundle b = new Bundle();
                    b.putLong("total", file.length());
                    b.putLong("count", count);
                    msg.setData(b);
                    handler.sendMessage(msg);
                }
                is.close();

                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                //*获取响应码 200=成功 当响应成功，获取响应的流
                int res = conn.getResponseCode();
                if (res == 200) {
                    // 读取返回数据
                    StringBuffer strBuf = new StringBuffer();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        strBuf.append(line).append("\n");
                    }
                    result = strBuf.toString();
                    reader.close();
                    return result;
                }
                dos.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_up_video:// 上传按钮
                showVideoSelect();
                break;
            case R.id.play_btn:// 播放按钮
                if (mVideoBean != null && !TextUtils.isEmpty(mVideoBean.getVideo())) {
                    mPlayBtnView.setVisibility(View.GONE);
                    videoView.setVisibility(View.VISIBLE);
                    videoView.setAutoHideController(false);
                    videoView.loadAndPlay(mVideoBean.getVideo(), 0, true);
                } else {
                    CUtils.showToast("地址获取失败");
                }
                break;
            case R.id.video_del_button:
                Tools.showSimpleDialog(context, "确认删除此视频故事", "取消", "删除", new Tools.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        removeVideo();
                    }

                    @Override
                    public void doCancel() {

                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof VideoBean) {
            mVideoBean = (VideoBean) data;
            if (mVideoBean != null && mVideoBean.getResCode() != null) {
                if (mVideoBean.getResCode().equals("0000")) {
                    setVideo();
                } else if (mVideoBean.getResCode().equals("0003")) {
                    setVideoVisibility(false);
                } else {
                    CUtils.showToast(mVideoBean.getMsg());
                }
            }
        } else if (data instanceof SimpleBean) {
            SimpleBean spb = (SimpleBean) data;
            if (spb != null && spb.getResCode() != null) {
                if (spb.getResCode().equals("0000")) {
                    CUtils.showToast("删除成功");
                    closeVideo();
                    setVideoVisibility(false);
                    getActivity().sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                } else {
                    CUtils.showToast(spb.getMsg());
                }
            }
        }
    }

    private void setVideo() {
        // 界面关联数据
        if (mVideoBean != null && !TextUtils.isEmpty(mVideoBean.getVideo())) {
            closeVideo();
            setVideoVisibility(true);
            final String pathPic = mVideoBean.getThumbnail();
            if (!TextUtils.isEmpty(pathPic)) {
                Glide.with(context)
                        .load(pathPic)
                        .placeholder(R.mipmap.bg_loadimage)
//                        .diskCacheStrategy(DiskCacheStrategy.NONE)
//                        .skipMemoryCache(true)
//                        .transform(myBitmapTransformation)
                        .into(video_bg_iv);
                // 根据图片大小设置控件大小
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String str = "";
                        try {
                            URL url = new URL(pathPic);
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            InputStream in = conn.getInputStream();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeStream(in, null, options);
                            int height = options.outHeight;
                            int width = options.outWidth;
                            if (height > 0 && width > 0) {
                                Message msg = handler.obtainMessage(12);
                                msg.arg1 = width;
                                msg.arg2 = height;
                                handler.sendMessage(msg);
                            }
                            str = "宽度是" + width + "高度是" + height;
                            LogUtil.i("jiehuntong", str);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else {
            setVideoVisibility(false);
        }
    }

    private void setVideoVisibility(boolean visibility) {
        if (visibility) {
            have_video_story_tv.setVisibility(View.GONE);
            no_video_story_ll.setVisibility(View.VISIBLE);
        } else {
            have_video_story_tv.setVisibility(View.VISIBLE);
            no_video_story_ll.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        CUtils.showToast("数据请求失败");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        closeVideo();
    }
}
